from flask import Flask,session,request,render_template,jsonify
import os
from backstage.auth import auth
import backstage.db as DB
app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False
app.secret_key = "!@#$%^&*()"
app.config['SECRET_KEY'] = os.urandom(24)  # 生成24位的随机数种子，用于产生SESSION ID
app.register_blueprint(auth,url_prefix="/sys")
@app.route('/')
def login():
    return render_template("login.html")

@app.route('/doLogin',methods=['POST'])
def doLogin():
    loginName=request.form.get("loginName")
    password=request.form.get("password")
    sql="select * from sys_user where loginName='{}' and password ='{}'".format(loginName,password)
    cursor=DB.controlDB(sql)
    resp={
        "msg":"登录成功",
        "code":200
    }
    list=cursor.fetchall()
    if(list.__len__()==1):
        session['curUser'] = (loginName, password)
    else:
        resp["msg"]="用户名或密码错误"
        resp["code"]=100
    return jsonify(resp)

@app.route('/registerAccount')
def registerAccount():
    return render_template("register.html")

@app.route('/registerUser',methods=['POST'])
def registerUser():
    loginName = request.form.get("loginName")
    password = request.form.get("password")
    realName = request.form.get("realName")
    email = request.form.get("email")
    selectSql = "select * from sys_user where loginName='{}' and password ='{}'".format(loginName, password)
    resp={
        "msg":"添加成功",
        "code":200
    }
    cursor = DB.controlDB(selectSql)
    list = cursor.fetchall()
    if (list.__len__() == 0):
        insertSql="insert into sys_user(loginName, password, realName, email) values('{loginName}','{password}','{realName}','{email}')".format(
            loginName=loginName,
            password=password,
            realName=realName,
            email=email)
        DB.controlDB(insertSql)
    else:
        resp["msg"] = "用户名或密码错误"
        resp["code"] = 100
    return jsonify(resp)
if __name__ == '__main__':
    app.run()
